﻿using Core.Configurations;
using Core.Interfaces;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Services
{
    public class MemoryCacheService : ICacheService
    {
        private readonly IMemoryCache _memoryCache;
        private readonly CacheConfiguration _cacheConfiguration;
        private readonly MemoryCacheEntryOptions _cacheCacheEntryOptions;
        public MemoryCacheService(IMemoryCache memoryCache, IOptions<CacheConfiguration> cacheConfiguration)
        {
            _memoryCache = memoryCache;
            _cacheConfiguration = cacheConfiguration.Value;
            if (cacheConfiguration != null) {
                _cacheCacheEntryOptions = new MemoryCacheEntryOptions();
                _cacheCacheEntryOptions.AbsoluteExpiration = DateTimeOffset.Now.AddHours(  _cacheConfiguration.AbsoluteExpirationInHours);
                _cacheCacheEntryOptions.SlidingExpiration=TimeSpan.FromMinutes( _cacheConfiguration.SlidingExpirationInMinutes);
               _cacheCacheEntryOptions.Priority= CacheItemPriority.High;
            }
        }


        public void Remove<T>(string cacheKey)
        {
            _memoryCache.Remove(cacheKey);
        }

        public T Set<T>(string cacheKey, T value)
        {
            return _memoryCache.Set(cacheKey, value,_cacheCacheEntryOptions);
        }

        public bool TryGet<T>(string cacheKey, out T value)
        {
            _memoryCache.TryGetValue(cacheKey, out value);
            if (value==null)
            {
                return false;
            }
            return true;
        }
    }
}
